package threadingexercise;



import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

// 基于阻塞队列的 生产者消费者模型
public class ThreadDemo20ProducerConsumers {
    public static void main(String[] args) {

        BlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
        //消费者
        Thread t1 = new Thread(() -> {
            int value = 0;

            while(true) {
                try {
                    value = queue.take();
                    System.out.println("消费元素：" + value);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        t1.start();


        //生产者
        Thread t2 = new Thread(() -> {
            int value = 0;
            while (true) {
                try {
                    queue.put(value);
                    System.out.println("生产元素：" + value);
                    value++;
                    //生产者 慢一些 ，此时消费者会阻塞等待
                    Thread.sleep(1000);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        t2.start();
    }
}